//
// Created by mmuee on 2024/4/24.
//

#ifndef YWZM_BUFFERVIEW_HPP
#define YWZM_BUFFERVIEW_HPP

#include "ByteBuffer.hpp"

template<typename Type>
struct BufferView
{
    bool _unmanaged{false};
    ByteBuffer* buffer{};
    explicit BufferView(ByteBuffer* buffer)
        : buffer(buffer), _unmanaged(true){};
    explicit BufferView(uint32_t length)
    {
        buffer = new ByteBuffer(length * stride());
    }
    explicit BufferView(uint32_t bufferLen, void* _buffer)
    {
        buffer = new ByteBuffer(bufferLen, _buffer, true);
    };
    ~BufferView()
    {
        if (!_unmanaged)
            delete buffer;
        buffer = nullptr;
    }

    int32_t stride() { return sizeof(Type); }
    int32_t length() { return buffer->size() / stride(); }
    Type& operator[](int32_t idx) const
    {
        return ((Type*)buffer->data())[idx];
    };
};

using Int64Buffer = BufferView<int64_t>;
using Int32Buffer = BufferView<int32_t>;
using Int16Buffer = BufferView<int16_t>;
using Int8Buffer = BufferView<int8_t>;
using FloatBuffer = BufferView<float>;

#endif //YWZM_BUFFERVIEW_HPP
